package ch.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/** Classe per la gestione della singola richiesta POP
 * 
 * @author Giovanni Franza - GPLv3 - 8/6/2011
 *
 */

public class POPWorker extends POP {
	private Socket socket;
	private POP pop;
	private int state=0;

	/** Construttore .
	 *
	 * @param socket - socket su cui opera
	 * @param pop - riferimenti al gestore di protocollo
	 * 
	 */

	public POPWorker( Socket socket, POP pop ) {
		this.socket = socket;
		this.pop = pop;
	}

	/** Il run fa tutto il lavoro.
	 *
	 */
	
	public void run() {
		try {
		    // Create streams to securely send and receive data to the client
			BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );				
			OutputStream out = socket.getOutputStream();	
		    // Read from in and write to out...
		    String page= new String( "\n" );
		    StateManager sm = new StateManager(pop.getStateManager());
		    out.write( sm.getWelcome().getBytes() );
		    for(int j=0;;j++) {
		    	String request = in.readLine();
		    	if( request == null ) {
		    		break;
		    	}
		    	sm.nextHop( request, state );
		    	out.write( sm.getResponse().getBytes() );
		    	if( sm.error() ) {
		    		break;
		    	}
		    	page = page.concat( request + "\n" );
		    }
			// close files
		    out.close();
		    in.close();
		} catch(IOException e) {
			System.out.println(e);
		}
	}
}
